package application.ratt.utils;

import android.annotation.SuppressLint;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class RoutesXMLParser extends DefaultHandler{

	private static ArrayList<Route> routes = new ArrayList<Route>();
	private ArrayList<TimeInStation> stations = new ArrayList<TimeInStation>();
	private StringBuilder buffer;
	
	private String name = "", line = "";
	private int time = 0;
	
	boolean routeTag = false;
	boolean stationTag = false;
	boolean nameTag = false;
	boolean timeTag = false;
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		buffer = new StringBuilder();
	}

	@SuppressLint("NewApi")
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {

		buffer.append(Arrays.copyOfRange(ch, start, start + length));

	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		if (qName.equalsIgnoreCase("route")) {
			Route route = null;
			try {
				route = new Route(stations);
			} catch (CloneNotSupportedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			routes.add(route);
			stations.clear();
		}

		if (qName.equalsIgnoreCase("station")) {
			TimeInStation station = new TimeInStation(name, line, time);
			stations.add(station);
		}
		
		if (qName.equalsIgnoreCase("name")) {
			name = buffer.toString();
		}
		
		if (qName.equalsIgnoreCase("line")) {
			line = buffer.toString();
		}
		
		if (qName.equalsIgnoreCase("time")) {
			time = Integer.parseInt(buffer.toString().trim());
		}
	}
	
	public static void parseXML(InputStream in){
		DefaultHandler dotsHandler = new RoutesXMLParser();
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser saxParser = factory.newSAXParser();
			saxParser.parse(in, dotsHandler);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static ArrayList<Route> getRoutes(){
		return routes;
	}
}
